<template>
  <!--工序的基本信息-->
  <basic-dialog v-model="dialog.showDialog" :title="dialog.title" width="1200"
                :autoClose="false" :hideFooter="true" @close="cancleForm">
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="工序信息" name="first">
        <el-descriptions :column="1" border :label-width="120" v-loading="processLoading">
          <el-descriptions-item label="工序号">
            {{ row.code }}
          </el-descriptions-item>
          <el-descriptions-item label="工步名称">
            {{ row.name }}
          </el-descriptions-item>
          <el-descriptions-item label="工序内容" >
            <div style="height:150px;">{{ row.processContent }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ row.sign }}
          </el-descriptions-item>
          <el-descriptions-item label="工艺附图">
            <div style="display: flex;height:215px">
              <div v-for="(item ,index) in base64Images" :key="index" style="margin-right: 10px;">
                <el-image
                    :preview-src-list="[item.imgurl]"
                    :src="item.imgurl"
                    fit="contain"
                    style="width: 100px; height: 100px">
                </el-image>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="待装零件" name="second">
        <basic-crud  ref="crudRef" :option="options" apiGetListUrl="/mpm/processController/listMaterial"
                     apiGetListMethod="post" :defaultListParams="{specificationTaskId: parentRow.id,processId: parentRow[props.idProp]}" :pageData="{pageSize:-1}"
                     :fastSearch="{name:'图号、名称',fastColumn:'code,name'}">
        </basic-crud>
      </el-tab-pane>
      <el-tab-pane label="资源列表" name="third">
        <basic-crud  ref="resourceCrudRef" :option="resourceOptions" apiGetListUrl="/mpm/processController/listDevice"
                     apiGetListMethod="post" :defaultListParams="{processId: parentRow[props.idProp]}" :pageData="{pageSize:-1}"
                     :fastSearch="{name:'型号、名称',fastColumn:'code,name'}">
        </basic-crud>
      </el-tab-pane>
      <el-tab-pane label="辅材列表" name="five">
        <basic-crud  ref="auxiliaryCrudRef" :option="auxiliaryOptions" apiGetListUrl="/mpm/processController/listAuxiliaryMaterials"
                     apiGetListMethod="post" :defaultListParams="{processId: parentRow[props.idProp]}" :pageData="{pageSize:-1}"
                     :fastSearch="{name:'编码、名称',fastColumn:'code,name'}">
        </basic-crud>
      </el-tab-pane>
      <el-tab-pane label="工序文档" name="fourth">
        <basic-crud  ref="fileCrudRef" :option="fileOptions" apiGetListUrl="/mpm/processController/listFile"
                     apiGetListMethod="post" :fastSearch="{processId: parentRow[props.idProp]}" :defaultListParams="{}"
                     :pageData="{pageSize:-1}">
          <template #name="{ row }">
            <el-button type="text" @click="downloadFileHandler(row)">{{row.name}}
            </el-button>
          </template>
        </basic-crud>
      </el-tab-pane>
    </el-tabs>
  </basic-dialog>
</template>

<script setup>
import {
  getMpmProcess,
  getMpmProcessFile,
  downloadFileInProcess
} from "@/apis/Techne/TechneDeails.js";
import {downloadFileByBlobHandler} from "@/utils/file.js";
import { formatDate } from "@/utils/formatTime";

import {defineExpose, ref} from "vue";
import {ElMessage} from "element-plus";
// 定义 props
const props = defineProps({
  // 自定义父组件传递的id键名
  idProp: {
    type: String,
    default: "processId",
  },
})
const dialog = ref({
  showDialog: false,
  title: "工序信息"
})
const parentRow = ref({});
//工序对象
const row=ref({})
const processLoading=ref(false)
// 打开新增编辑对话框
const openDialog = (row) => {
  dialog.value.showDialog = true;
  parentRow.value=row;
  getProcessInfo();
  imgCreatedHandler();
};
//待装零件
const options= {
  addBtn: false,
  editBtn:false,
  delBtn:false,
  align: "center",
  height: "470px",
  menu: false,
  showPage:false,
  column: [
    {
      label: "图号",
      prop: "code",
    },
    {
      label: "类型",
      prop: "partType",
    },
    {
      label: "名称",
      prop: "name",
    },
    {
      label: "消耗类型",
      prop: "partType",
      sort: true,
      width:120,
    },
    {
      label: "需求数量",
      prop: "quantity",
      sort: true,
      width:100,
    },
    {
      label: "单位",
      prop: "unit",
      sort: true,
      width:100,
    },
  ]
}
//资源列表
const resourceOptions={
  addBtn: false,
  editBtn:false,
  delBtn:false,
  menu: false,
  cellBtn: true,
  height: "470px",
  showPage:false,
  column: [
    {
      label: "型号/规格",
      prop: "code",
    },
    {
      label: "名称",
      prop: "name",
    },
    {
      label: "类型",
      prop: "type",
      width:120,
    },
    {
      label: "供应商",
      prop: "supplier",
    },
    {
      label: "备注",
      prop: "remark",
    },
  ]
}

//辅材列表
const auxiliaryOptions={
  addBtn: false,
  editBtn:false,
  delBtn:false,
  menu: false,
  cellBtn: true,
  height: "470px",
  showPage:false,
  column:  [
    {
      label: "编码",
      prop: "code",
    },
    {
      label: "名称",
      prop: "name",
    },
  ]
}
//工序文档
const fileOptions={
  addBtn: false,
  editBtn:false,
  delBtn:false,
  menu: false,
  cellBtn: true,
  height: "470px",
  showPage:false,
  column:  [
    {
      label: "文档",
      prop: "name",
      sort: true,
      slot: true,
    },
    {
      label: "文件类别",
      prop: "type",
      width:120,
    },
    {
      label: "上传时间",
      prop: "createTime",
      width:120,
      formatter: (row) => {
        return formatDate(row.createTime, "yyyy-MM-dd");
      },
    },
    {
      label: "更新时间",
      prop: "modifyTime",
      sort: true,
      width:120,
      formatter: (row) => {
        return formatDate(row.createTime, "yyyy-MM-dd");
      },
    },
    {
      label: "有效性",
      prop: "deviceType",
      width:150,
      sort: true,
    },
  ]
}
const activeName=ref('first');
const handleClick=(tab) =>{
  activeName.value = tab.name;
}

// 转换响应头二进制数据格式
const getMediaType=(val)=>{
  if (!val) {
    return 'application/octet-stream';
  }
  return `image/${val}`;
}
// 初始化图片
const imgCreatedHandler=()=> {
  // 定义图片格式后缀
  const imgType = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'bmp', 'tga', 'img', 'image', 'webp'];

  // 先请求接口 过滤出来符合标准的图片
  let params = {};
  params.ownId = parentRow.value[props.idProp];

  getMpmProcessFile(params).then((resdata) => {
    const filteredImages = resdata.filter(item => {
      // 检查fileExtension属性是否存在于imgType数组中
      return imgType.includes(item.fileExtension);
    });

    if (filteredImages && filteredImages.length > 0) {
      Promise.all(filteredImages.map(row => {
        return downloadFileInProcess({id: row.id}).then(filedata => {
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = function () {
              if (!reader.error) {
                // 当读取成功时，返回 Data URL
                resolve({
                  dataUrl: reader.result,
                  fileExtension: row.fileExtension
                });
              } else {
                // 如果读取失败拒绝Promise
                reject(reader.error);
              }
            };
            reader.onerror = reject;
            reader.readAsDataURL(filedata);
          });
        });
      })).then(base64Images => {
        let base64List = base64Images.value.map(({dataUrl, fileExtension}) => {
          const base64Data = dataUrl.split(',')[1];
          let mediaType = getMediaType(fileExtension);
          let newBase64String = `data:${mediaType};base64,${base64Data}`;
          return {imgurl: newBase64String};
        });
        base64Images.value = base64List;
      }).catch(error => {
        ElMessage.error("文件下载或读取失败!");
      });
    }
  });
}

//工序详情
const getProcessInfo=() => {
  getMpmProcess({id: parentRow.value[props.idProp]},processLoading).then((resdata) => {
    if (resdata.length > 0) {
      row.value = resdata[0];
    }
  })
}

const base64Images=ref([])
const downloadLoading = ref(false);
const downloadFileHandler=(row) =>{
  // 接口名(传递row.id).then(res => {
  //   downloadFileByBlobHandler(res)
  // })
  // 接口api加上响应类型： responseType: 'blob',
  downloadFileInProcess({id: row.id},downloadLoading).then(res => {
    downloadFileByBlobHandler(res,downloadLoading);
  });
}

const crudRef=ref(null);
const resourceCrudRef=ref(null);
const auxiliaryCrudRef=ref(null)
const fileCrudRef=ref(null)
// 取消
const cancleForm=()=> {
  activeName.value = "first";
  crudRef.value.tableData = [];
  resourceCrudRef.value.tableData = [];
  auxiliaryCrudRef.value.tableData = [];
  fileCrudRef.value.tableData = [];
}
defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
::v-deep{
  .el-tab-pane{
    height: 500px;
  }
}
</style>